package org.eweb4j.solidbase.main.web;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;

import org.eweb4j.component.dwz.DWZ;
import org.eweb4j.component.dwz.DWZCons;
import org.eweb4j.component.dwz.menu.navmenu.NavMenu;
import org.eweb4j.ioc.IOC;
import org.eweb4j.mvc.action.annotation.Controller;
import org.eweb4j.orm.dao.DAOFactory;
import org.eweb4j.solidbase.main.model.MainCons;
import org.eweb4j.solidbase.main.model.MainModelView;


/**
 * 默认控制器，负责后台主页的显示，统计等操作。
 * 
 * @author weiwei
 * 
 */
@Controller
@Path("${MainConstant.MODEL_NAME}")
public class MainControl {
	private HttpServletRequest request = null;
	private Long navMenuId = null;
	private PrintWriter out = null;
	private String pageName = null;

	private DWZ dwz = IOC.getBean(DWZCons.IOC_DWZ_BEAN_ID());

	private final static String format = "<div class=\"accordion\" fillSpace=\"sideBar\">%s</div>";

	/**
	 * 显示后台界面
	 * 
	 * @return
	 */
	@GET
	@Path("/")
	public String doGet() {
		String treeMenus = null;
		try {
			treeMenus = dwz.getAccordion(MainCons.DEFAULT_NAV_MENU_NAME());
		} catch (Exception e) {
			return dwz.getFailedJson(e.getMessage()).toString();
		}

		List<NavMenu> navMenus = DAOFactory.getSelectDAO().selectAll(
				NavMenu.class, "rank", 1);
		MainModelView mmv = new MainModelView();
		mmv.setTitle(MainCons.TITLE());
		mmv.setNavMenus(navMenus);
		mmv.setTreeMenus(treeMenus);
		mmv.setCopyRight(MainCons.COPY_RIGHT());

		request.setAttribute("MainModel", mmv);

		return "forward:main/view/main.jsp";
	}

	/**
	 * 切换导航菜单
	 * 
	 * @return
	 */
	@GET
	@POST
	@Path("/switchEnv/{navMenuId}")
	public String switchEnvHandler() {
		String menu = null;
		try {
			menu = dwz.getAccordion(navMenuId);
			return String.format(format, menu);
		} catch (Exception e) {
			return dwz.getFailedJson(e.getMessage()).toString();
		}
	}

	@GET
	@POST
	@Path("/switchEnv/{pageName}.html")
	public String doSwitchPage1() {

		return "forward:main/view/" + pageName + ".html";
	}

	@GET
	@POST
	@Path("/switchEnv/{pageName}.jsp")
	public String doSwitchPage2() {
		return "forward:main/view/" + pageName + ".jsp";
	}

	@Path("/about-us")
	@POST
	@GET
	public String doAboutUs(){
		return "forward:main/view/about.jsp";
	}
	
	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public Long getNavMenuId() {
		return navMenuId;
	}

	public void setNavMenuId(Long navMenuId) {
		this.navMenuId = navMenuId;
	}

	public String getPageName() {
		return pageName;
	}

	public void setPageName(String pageName) {
		this.pageName = pageName;
	}

	public PrintWriter getOut() {
		return out;
	}

	public void setOut(PrintWriter out) {
		this.out = out;
	}

}
